/**
 * Created by zhoulin on 2019/4/3.
 */
var companyId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.companyId);
var schoolId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolId);
var schoolMap = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolMap);

var updateObject = {};
var updateId = '';
//表格初始化配置
var tableInit = function () {
    var columns = [
        {
            field: 'selectItem',
            checkbox: true
        },
        {
            field: 'applyName',
            title: '申请者公司',
            align: 'center',
            valign: 'middle',
        },
        {
            field: 'applyImgUrl',
            title: '申请者公司LOGO',
            align: 'center',
            formatter: function (value) {
                if (!empty(value)) {
                    var img_html = "<a href='" + value + "' title='点击查看大图' target='_blank'>" +
                        "<img src='" + value + "' width='40' onerror='imgNotfind(event);' /></a>";
                    return img_html;
                } else {
                    return "<img src='" + value + "' width='40' onerror='imgNotfind(event);' />";
                }
            }
        },
        {
            field: 'beApplyName',
            title: '被申请公司',
            align: 'center',
            valign: 'middle',
        },
        {
            field: 'beApplyImgUrl',
            title: '被申请公司LOGO',
            align: 'center',
            formatter: function (value) {
                if (!empty(value)) {
                    var img_html = "<a href='" + value + "' title='点击查看大图' target='_blank'>" +
                        "<img src='" + value + "' width='40' onerror='imgNotfind(event);' /></a>";
                    return img_html;
                } else {
                    return "<img src='" + value + "' width='40' onerror='imgNotfind(event);' />";
                }
            }
        },
        {
            field: 'type',
            title: '类别',
            align: 'center',
            formatter: function (value, row, index) {
                if (value == 1) return '<span class="label label-default">向上申请</span>';
                if (value == 2) return '<span class="label label-success">向下授予</span>';
            }
        },
        {
            field: 'status',
            title: '状态',
            align: 'center',
            formatter: function (value, row, index) {
                if (value == -1) return '<span class="label label-warning">发起方中断合作</span>';
                if (value == 0) return '<span class="label label-warning">接收方中断合作</span>';
                if (value == 1) return '<span class="label label-default">待同意</span>';
                if (value == 2) return '<span class="label label-success">合作中</span>';
            }
        },
        {
            field: 'status',
            title: '申请/中断理由',
            align: 'center',
            formatter: function (value, row, index) {
                if (value == 1) {
                    return row.applyReason;
                } else if (value == 2) {
                    return '-';
                } else {
                    return row.interruptReason;
                }
            }
        },
        {
            field: 'gmtCreate',
            title: '创建时间',
            align: 'center',
            width: '150px',
            formatter: function (value, index) {
                return formatDateTime(value);
            }
        }
    ];

    //请求服务数据时所传参数
    function queryParams(params) {
        return {
            pageNo: params.pageNumber,
            pageSize: params.pageSize,
            status: $("#status").val(),
            companyId: companyId,
            schoolId: schoolId,
            searchText: params.searchText,
            sortName: params.sortName,      //排序列名
            sortOrder: params.sortOrder //排位命令（desc，asc）
        }
    }

    var tableConfig = $.extend(bootstrapTableConfig(_HOST + _API.product_cooperateApply_list, queryParams, columns), {
        //这里是其他的一些个性化的 bootstrap-table options
        //例如 覆盖一些公共的配置
        //例如 添加一些私有的配置
        showColumns: true,//列显示操作按钮
        ajaxOptions: { //设置自定义请求头
            headers: {
                'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
                'permCoding': 'companyCooperateApply:list'
            }
        },
        //例如格式化数据
        responseHandler: function (res) {
            //在ajax获取到数据，渲染表格之前，修改数据源
            //console.log(res)
            if (res.list) {
                for (let i = 0; i < res.list; i++) {

                }
            }
            if (res.success) {
                //更新本地token
                sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.token, res.token);
            }
            return res;
        }
    });
    //调用实例化
    $('#bootstrapTableEvents').bootstrapTable(tableConfig);
    $(".search input").attr('placeholder', '输入公司名字搜索');
};

var app = new Vue({
    el: '#app',
    data: {
        permissions: ['companyCooperateApply:add', 'companyCooperateApply:update', 'companyCooperateApply:delete', 'companyCooperateApply:list'],//本页权限数组
        applyReason: '',
        interruptReason: '',
        status: '',
        brandList: [],
        canConfirm: false,
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        that.initBrandList();
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if (empty(token)) {
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon: 5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            }, 1200);

            return;
        }
    },
    methods: {
        selectStatus: function () {
            $('#bootstrapTableEvents').bootstrapTable('refresh');
        },
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        //添加
        add: function () {
            var that = this;
            var index = layer.open({
                type: 2,
                title: "新增",
                content: "edit.html?id=",
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['70%', '70%'],
                maxmin: true, //开启最大化最小化按钮
            });
            layer.full(index);
        },
        //修改
        update: function () {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0 || list.length > 1) {
                layer.msg('请选中一条数据', {time: 1500, icon: 5});
                return;
            }
            updateObject = list[0];
            that.applyReason = updateObject.applyReason;
            that.interruptReason = updateObject.interruptReason;
            if (empty(updateObject.interruptReason)) {
                that.interruptReason = "";
            }
            if (updateObject.status < 0) {
                that.status = 0;
            } else {
                that.status = updateObject.status;
            }
            that.canConfirm = false;
            if (updateObject.cooperateCompanyId == companyId) {
                that.canConfirm = true;
            }
            layer.open({
                type: 1,
                area: ['550px', ''],
                content: $('#select')
            });
        },
        delUpdate: function () {
            var that = this;
            if (that.status == '0') {
                if (updateObject.companyId == companyId) {
                    that.status = -1;
                }
            }
            updateObject.interruptReason = that.interruptReason;
            updateObject.status = that.status;

            Post(that, _HOST + _API.product_cooperateApply_update, updateObject, true, that.permissions[1])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    $('#bootstrapTableEvents').bootstrapTable('refresh');
                    if (response) {
                        if (response.success) {
                            layer.closeAll();
                            layer.msg(response.msg, {time: 1500, icon: 1});
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                })
        },
        initBrandList: function () {
            var that = this;
            // 得到brandlist
            Get(that, _HOST + _API.product_goodsBrand_list + "?companyId=" + companyId + "&schoolId=" + schoolId)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            that.brandList = response.rows;
                            // 初始化选择插件
                            setTimeout(function () {
                                selectImgTake.init('selectItemDiv', 100);
                            }, 500);
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                });
        },
        // 授权品牌
        auth: function () {
            var that = this;
            selectImgTake.cancelSelected('selectItemDiv');
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0 || list.length > 1) {
                layer.msg('请选中一条数据', {time: 1500, icon: 5});
                return;
            }
            updateId = list[0].id;
            if (list[0].status != 2) {
                layer.msg('仅合作中可操作！', {time: 1500, icon: 5});
                return;
            }
            // 权限判定
            if (list[0].type==1) {
                // 向上申请
                if (companyId != list[0].cooperateCompanyId) {
                    layer.msg('无权操作！', {time: 1500, icon: 5});
                    return;
                }
            } else if (list[0].type==2) {
                // 向下授予
                if (companyId != list[0].companyId) {
                    layer.msg('无权操作！', {time: 1500, icon: 5});
                    return;
                }
            }
            // 初始化选中
            selectImgTake.selectItems('selectItemDiv',list[0].brands.split(","));

            layer.open({
                type: 1,
                area: ['950px', ''],
                content: $('#brands')
            });
        },
        // 确定授权
        confirmAuth: function () {
            var that = this;
            var items = selectImgTake.getSelectImgs('selectItemDiv', 100);
            var ids = [];
            items.each(function (index, item) {
                ids.push(item.getAttribute("data-item"))
            });
            Post(that, _HOST + _API.product_cooperateApply_authBrand + "?id=" + updateId + "&ids=" + ids.join(","), {}, true)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    layer.closeAll();
                    $('#bootstrapTableEvents').bootstrapTable('refresh');
                    if (response) {
                        if (response.success) {
                            layer.msg(response.msg, {time: 1500, icon: 1});
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                })
        },
        //删除
        del: function (index) {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0) {
                layer.msg('请至少选中一条数据', {time: 1500, icon: 5});
                return;
            }

            var ids = "";
            for (let i = 0; i < list.length; i++) {
                ids += list[i].id;
                if ((i + 1) != list.length) {
                    ids += ",";
                }
            }

            var confirm = layer.confirm('确定删除选中项？', {
                btn: ['确定', '取消'], //按钮
                shadeClose: false,
            }, function () {
                Post(that, _HOST + _API.product_cooperateApply_delete + "?ids=" + ids, {}, true, that.permissions[index])
                    .then(function (response) {
                        // 响应成功回调
                        console.log(response);
                        layer.close(confirm);
                        $('#bootstrapTableEvents').bootstrapTable('refresh');
                        if (response) {
                            if (response.success) {
                                layer.msg(response.msg, {time: 1500, icon: 1});
                            } else {
                                layer.msg(response.msg, {time: 1500, icon: 5});
                            }
                        }
                    })
            });

        },
    },
});

$(function () {
    //初始化表格
    tableInit();
});
